package com.wxy.gsx.springbootprojectday21_2.controller;

import com.alibaba.fastjson.JSON;
import com.wxy.gsx.springbootprojectday21_2.bean.RequestAccessTockenParam;
import com.wxy.gsx.springbootprojectday21_2.bean.UserInfo;
import com.wxy.gsx.springbootprojectday21_2.utils.HttpHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


@Controller
public class AuthController {
    @Autowired
    private HttpHelper httpHelper;
    String client_id = "89804c4a3788e1ebd36b";
    String client_secret = "b8c5382838e73cec39e19c6bfd8dca575601823b";
    @RequestMapping("/user/login")
    @ResponseBody
    public UserInfo callback(@RequestParam("code") String code,@RequestParam("state") String state,HttpSession session) {
        System.out.println("这是返回回来的参数信息"+code);

        RequestAccessTockenParam param=new RequestAccessTockenParam();

        //用户的id
        param.setClient_id(client_id);
        //用户的密钥
        param.setClient_secret(client_secret);
        //传递过来的参数
        param.setCode(code);//传入code参数
        //二次请求的地址
        param.setRedirect_url("http://localhost:8090");
        //设置状态
        param.setState(state);
        //获取access token
        String url="https://github.com/login/oauth/access_token";
        //将数据转化成json的数据格式
        String json= JSON.toJSONString(param);
        System.out.println("封装的数据类型:  "+json);
        //2.根据传入的参数（包含code），post请求https://github.com/login/oauth/access_token，获取返回值
        //通过自己编写请求的方式
        String result= httpHelper.Post(url,json);//access_token=your_client_id&scope=user&token_type=bearer
        System.out.println( "callback result:"+result);

        String[] strs=result.split("&");
        String access_token=strs[0].split("=")[1];//解析access_token

        //3.根据access token,请求https://api.github.com/user获取用户信息
        System.out.println("这是令牌"+access_token);
        String url_user="https://api.github.com/user?access_token="+access_token;
        //https://api.github.com/user?access_token=xxx
        String userInfo=httpHelper.Get(url_user);
        System.out.println("userInfo:"+userInfo);//返回的是一个json字符串
//
        UserInfo user=JSON.parseObject(userInfo,UserInfo.class);





        return user;
    }
    @RequestMapping("/")
    public String method01(){
        return "index";

    }

    /**
     * 总的思路:
     *  1.需要这是自己的回调地址,这里面会传递进来两个参数,一个就是code,一个就是state
     *  2.通过第三方调用回到地址将上面的参数传递过来,获取到上面的两个参数之后,在获取到令牌
     *  3.通过获取到令牌在获取到用户的信息
     *
     *
     *
     */

}
